package codeTop;

public class q695 {
    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        boolean[][] visit = new boolean[m][n];
        int num = 0;
        for (int i = 0; i <m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visit[i][j] && grid[i][j] == 1) {
                    num = Math.max(num,dfs(i,j,grid,visit,m,n));
                }
            }
        }
        return num;
    }

    private int dfs(int i, int j, int[][] grid, boolean[][] visit, int m, int n) {
        visit[i][j] = true;
        int num = 1;
        //上
        if (i>0&&grid[i-1][j]==1&&!visit[i-1][j]){
            num+=dfs(i-1,j,grid,visit,m,n);

        }
        //下
        if (i<m-1&&grid[i+1][j]==1&&!visit[i+1][j]){
            num+=dfs(i+1,j,grid,visit,m,n);
        }
        //左
        if (j>0&&grid[i][j-1]==1&&!visit[i][j-1]){
            num+=dfs(i,j-1,grid,visit,m,n);
        }
        //右
        if (j<n-1&&grid[i][j+1]==1&&!visit[i][j+1]){
            num+=dfs(i,j+1,grid,visit,m,n);
        }
        return num;
    }
}
